import time
import threading
from iClouds.libs import header_has_guuid
from iClouds.jobs import zombie
import random


class roomManager(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
        self.guid = header_has_guuid()
        self.isRun = True  # 是否运行
        self.sleep = 3  # 等待就绪秒数
        self.lastMoney = 100  # 上局结余金币
        self.money = 100  # 初始金币
        self.maxPlayer = 4
        self.player = set()  # 玩家合集
        self.zombie = set()  # 僵尸合集
        self.level = 1  # 当前关卡
        self.status = "wait"
        self.hp = 100  # 生命值

        self.curSleep = 20  # 刷怪间隔延迟
        self.curBatch = 0  # 当前批次
        self.maxBatch = 5  # 最大批次
        self.maxTools = 4  # 最大道具范围
        self.maxZombie = 10  # 最大关卡的僵尸数量

        self.data = {
            "curTrack": 5,  # 最大开放的轨道
            "curPlant": 20,  # 最大关卡的植物范围
            "curZombie": 20,  # 最大关卡的僵尸范围
            "curJewwlry": 20,  # 最大关卡的道具范围
            "curbatch": 10,  # 最大刷怪批次
            "curFund": 10,  # 最大刷怪数量
        }
        # 初始化
        self.initialization()

    def stop(self):
        self.isRun = False

    def run(self):
        print(f"创建房间 {self.name}")
        while self.isRun:
            time.sleep(1)
            if self.status == "wait":
                if self.checkPlayerStatus():
                    self.status = "lock"
                    self.changePlayerStatus("lock")
            elif self.status == "lock":
                for i in range(self.sleep):
                    self.alertAIring(
                        {
                            "act": "lock",
                            "guid": "room",
                            "code": 200,
                            "data": self.sleep - i,
                        }
                    )
                    time.sleep(1)
                # 发送初始数据
                self.alertAIring(
                    {"act": "money", "guid": "room", "code": 200, "data": self.money}
                )
                # 刷新1个僵尸
                # z = zombie(self, 3, 1)
                # z.start()
                # self.zombie.add(z)
                # 开始战斗
                self.status = "fight"
                self.changePlayerStatus("fight")
                self.ontime = time.time()  # 开始时间
                # self.last = time.time()  # 上次刷怪
                self.alertAIring(
                    {"act": "fight", "guid": "room", "code": 200, "data": self.level}
                )
                self.enableAiPlayer()
            elif self.status == "fight":
                if not len(self.player):
                    print("结束关卡:逃跑")
                    self.over = time.time()
                    self.status = "wait"
                    self.initialization(-1)
                elif self.hp <= 0:
                    print("结束关卡:失败")
                    self.over = time.time()
                    self.alertAIring({"act": "lose", "guid": "room", "code": 200})
                    self.status = "wait"
                    self.initialization(0)
                elif len(self.zombie) == 0:
                    if self.curBatch + 1 == self.maxBatch:
                        print("结束关卡:胜利")
                        self.over = time.time()
                        self.alertAIring({"act": "win", "guid": "room", "code": 200})
                        self.status = "wait"
                        self.lastMoney = self.money
                        self.initialization(1)
                else:  # 批次刷怪
                    if (
                        time.time() - self.last > self.curSleep
                        and self.curBatch < self.maxBatch
                    ):
                        self.enableAiPlayer()
        print(f"房间关闭 {self.name}")

    def initialization(self, idx=0):
        """初始化"""
        for i in self.zombie:
            i.stop()
            i.join()
        self.guid = header_has_guuid()
        self.hp = 100
        if idx < 0:
            self.level = 0
            self.money = 100
        elif idx > 0:
            self.level += 1
        else:
            self.money = self.lastMoney

    def alertAIring(self, data):
        """广播消息"""
        for player in self.player:
            player.snedMessage(data)

    def checkPlayerStatus(self):
        """检测玩家状态是否就绪"""
        if not len(self.player):
            return False
        state = True
        for i in self.player:
            if i.status == "wait":
                state = False
        return state

    def changePlayerStatus(self, state):
        """修改玩家状态"""
        for i in self.player:
            i.status = state

    def enableAiPlayer(self):
        """批次刷怪"""
        print("当前批次:", self.curBatch, "/", self.maxBatch)
        # 加载轨道刷怪范围的列表
        attacker = (
            range(5)
            if self.level > 0
            else [
                2,
            ]
        )
        # 最大僵尸数
        at = (self.curBatch + 1) * 2 + self.level
        # 特殊僵尸数
        mt = [random.choice(range(self.maxTools)) for x in range(self.curBatch + 1)]
        print("僵尸: 数量,特殊", at, mt)
        for track in attacker:
            for i in range(at):
                js = zombie(self, track, 0)  # random.choice(range(zt + 1)))
                if len(mt) and random.choice(range(6)) == 1:
                    js.setTools(mt.pop())
                js.start()
                self.zombie.add(js)
                time.sleep(random.choice(range(5)))
            time.sleep(random.choice(range(5)))

        # 更新批次
        self.curBatch += 1
        self.last = time.time()

    def findZombieFromGuid(self, guid):
        """通过guid查找对象"""
        for i in self.zombie:
            if i.guid == guid:
                return i
        else:
            return False
